<template>
  <div class="wechat-cloud-test">
    <t-card title="微信云开发测试" class="test-card">
      <template #actions>
        <t-button theme="primary" @click="connectToCloud" :loading="connecting">
          {{ cloudConnected ? '已连接' : '连接微信云' }}
        </t-button>
      </template>
      
      <!-- 连接状态 -->
      <div class="connection-status">
        <t-tag :theme="cloudConnected ? 'success' : 'warning'" variant="light">
          <t-icon :name="cloudConnected ? 'check-circle' : 'time'" />
          {{ cloudConnected ? '微信云已连接' : '未连接微信云' }}
        </t-tag>
        <span class="status-text">
          环境ID: {{ envId || '未设置' }}
        </span>
      </div>
    </t-card>

    <!-- 功能测试区域 -->
    <t-row :gutter="16" class="test-sections">
      <!-- 数据库测试 -->
      <t-col :span="6">
        <t-card title="数据库测试" class="function-card">
          <div class="test-actions">
            <t-button 
              block 
              variant="outline" 
              @click="testDatabase" 
              :loading="dbTesting"
              :disabled="!cloudConnected"
            >
              测试数据库连接
            </t-button>
            <t-button 
              block 
              variant="outline" 
              @click="addTestData" 
              :loading="addingData"
              :disabled="!cloudConnected"
            >
              添加测试数据
            </t-button>
            <t-button 
              block 
              variant="outline" 
              @click="queryTestData" 
              :loading="queryingData"
              :disabled="!cloudConnected"
            >
              查询测试数据
            </t-button>
          </div>
          
          <div class="test-result" v-if="dbResult">
            <t-divider>测试结果</t-divider>
            <pre>{{ JSON.stringify(dbResult, null, 2) }}</pre>
          </div>
        </t-card>
      </t-col>

      <!-- 云函数测试 -->
      <t-col :span="6">
        <t-card title="云函数测试" class="function-card">
          <div class="test-actions">
            <t-input 
              v-model="cloudFunctionName" 
              placeholder="输入云函数名称"
              class="function-input"
            />
            <t-button 
              block 
              variant="outline" 
              @click="callCloudFunction" 
              :loading="functionCalling"
              :disabled="!cloudConnected || !cloudFunctionName"
            >
              调用云函数
            </t-button>
            <t-button 
              block 
              variant="outline" 
              @click="listCloudFunctions" 
              :loading="listingFunctions"
              :disabled="!cloudConnected"
            >
              获取函数列表
            </t-button>
          </div>
          
          <div class="test-result" v-if="functionResult">
            <t-divider>调用结果</t-divider>
            <pre>{{ JSON.stringify(functionResult, null, 2) }}</pre>
          </div>
        </t-card>
      </t-col>

      <!-- 文件存储测试 -->
      <t-col :span="6">
        <t-card title="文件存储测试" class="function-card">
          <div class="test-actions">
            <t-upload
              v-model="uploadFiles"
              theme="file-input"
              :auto-upload="false"
              accept="image/*"
              :max="1"
              placeholder="选择图片文件"
            />
            <t-button 
              block 
              variant="outline" 
              @click="uploadToCloud" 
              :loading="uploading"
              :disabled="!cloudConnected || !uploadFiles.length"
            >
              上传到云存储
            </t-button>
            <t-button 
              block 
              variant="outline" 
              @click="listCloudFiles" 
              :loading="listingFiles"
              :disabled="!cloudConnected"
            >
              获取文件列表
            </t-button>
          </div>
          
          <div class="test-result" v-if="storageResult">
            <t-divider>存储结果</t-divider>
            <pre>{{ JSON.stringify(storageResult, null, 2) }}</pre>
          </div>
        </t-card>
      </t-col>

      <!-- 用户管理测试 -->
      <t-col :span="6">
        <t-card title="用户管理测试" class="function-card">
          <div class="test-actions">
            <t-button 
              block 
              variant="outline" 
              @click="getCurrentUser" 
              :loading="gettingUser"
              :disabled="!cloudConnected"
            >
              获取当前用户
            </t-button>
            <t-button 
              block 
              variant="outline" 
              @click="getUserList" 
              :loading="gettingUserList"
              :disabled="!cloudConnected"
            >
              获取用户列表
            </t-button>
            <t-button 
              block 
              variant="outline" 
              @click="testUserAuth" 
              :loading="testingAuth"
              :disabled="!cloudConnected"
            >
              测试用户认证
            </t-button>
          </div>
          
          <div class="test-result" v-if="userResult">
            <t-divider>用户信息</t-divider>
            <pre>{{ JSON.stringify(userResult, null, 2) }}</pre>
          </div>
        </t-card>
      </t-col>
    </t-row>

    <!-- 配置设置 -->
    <t-card title="微信云配置" class="config-card">
      <t-form :data="cloudConfig" label-width="120px">
        <t-row :gutter="16">
          <t-col :span="6">
            <t-form-item label="环境ID" name="envId">
              <t-input v-model="cloudConfig.envId" placeholder="输入微信云环境ID" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="AppID" name="appId">
              <t-input v-model="cloudConfig.appId" placeholder="输入小程序AppID" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="AppSecret" name="appSecret">
              <t-input 
                v-model="cloudConfig.appSecret" 
                type="password" 
                placeholder="输入小程序AppSecret" 
              />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="操作">
              <t-button @click="saveCloudConfig" theme="primary">保存配置</t-button>
              <t-button @click="loadCloudConfig" variant="outline">加载配置</t-button>
            </t-form-item>
          </t-col>
        </t-row>
      </t-form>
    </t-card>

    <!-- 实时日志 -->
    <t-card title="操作日志" class="log-card">
      <template #actions>
        <t-button size="small" variant="text" @click="clearLogs">清空日志</t-button>
      </template>
      
      <div class="log-container">
        <div 
          v-for="(log, index) in logs" 
          :key="index" 
          :class="['log-item', `log-${log.type}`]"
        >
          <span class="log-time">{{ log.time }}</span>
          <span class="log-message">{{ log.message }}</span>
        </div>
        <div v-if="!logs.length" class="no-logs">暂无日志</div>
      </div>
    </t-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'

// 连接状态
const cloudConnected = ref(false)
const connecting = ref(false)
const envId = ref('')

// 各功能测试状态
const dbTesting = ref(false)
const addingData = ref(false)
const queryingData = ref(false)
const functionCalling = ref(false)
const listingFunctions = ref(false)
const uploading = ref(false)
const listingFiles = ref(false)
const gettingUser = ref(false)
const gettingUserList = ref(false)
const testingAuth = ref(false)

// 测试结果
const dbResult = ref(null)
const functionResult = ref(null)
const storageResult = ref(null)
const userResult = ref(null)

// 表单数据
const cloudFunctionName = ref('hello')
const uploadFiles = ref([])

// 云配置
const cloudConfig = reactive({
  envId: '',
  appId: '',
  appSecret: ''
})

// 日志系统
const logs = ref([])

// 添加日志
const addLog = (message, type = 'info') => {
  logs.value.unshift({
    time: new Date().toLocaleTimeString(),
    message,
    type
  })
  
  // 限制日志数量
  if (logs.value.length > 100) {
    logs.value = logs.value.slice(0, 100)
  }
}

// 清空日志
const clearLogs = () => {
  logs.value = []
  addLog('日志已清空', 'info')
}

// 连接微信云
const connectToCloud = async () => {
  connecting.value = true
  addLog('正在连接微信云...', 'info')
  
  try {
    // 模拟连接过程
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    // 这里应该是真实的微信云初始化代码
    // wx.cloud.init({
    //   env: cloudConfig.envId
    // })
    
    cloudConnected.value = true
    envId.value = cloudConfig.envId || 'test-env-id'
    addLog('微信云连接成功', 'success')
    MessagePlugin.success('微信云连接成功')
  } catch (error) {
    addLog(`连接失败: ${error.message}`, 'error')
    MessagePlugin.error('微信云连接失败')
  } finally {
    connecting.value = false
  }
}

// 测试数据库
const testDatabase = async () => {
  dbTesting.value = true
  addLog('测试数据库连接...', 'info')
  
  try {
    // 模拟数据库测试
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    const result = {
      status: 'success',
      message: '数据库连接正常',
      collections: ['users', 'orders', 'products'],
      timestamp: new Date().toISOString()
    }
    
    dbResult.value = result
    addLog('数据库测试完成', 'success')
    MessagePlugin.success('数据库连接正常')
  } catch (error) {
    addLog(`数据库测试失败: ${error.message}`, 'error')
    MessagePlugin.error('数据库测试失败')
  } finally {
    dbTesting.value = false
  }
}

// 添加测试数据
const addTestData = async () => {
  addingData.value = true
  addLog('添加测试数据...', 'info')
  
  try {
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const result = {
      _id: 'test_' + Date.now(),
      name: '测试用户',
      email: 'test@example.com',
      createdAt: new Date().toISOString()
    }
    
    dbResult.value = result
    addLog('测试数据添加成功', 'success')
    MessagePlugin.success('测试数据添加成功')
  } catch (error) {
    addLog(`添加数据失败: ${error.message}`, 'error')
    MessagePlugin.error('添加数据失败')
  } finally {
    addingData.value = false
  }
}

// 查询测试数据
const queryTestData = async () => {
  queryingData.value = true
  addLog('查询测试数据...', 'info')
  
  try {
    await new Promise(resolve => setTimeout(resolve, 1200))
    
    const result = {
      total: 5,
      data: [
        { _id: '1', name: '用户1', status: 'active' },
        { _id: '2', name: '用户2', status: 'inactive' },
        { _id: '3', name: '用户3', status: 'active' }
      ]
    }
    
    dbResult.value = result
    addLog('数据查询完成', 'success')
    MessagePlugin.success('数据查询完成')
  } catch (error) {
    addLog(`查询数据失败: ${error.message}`, 'error')
    MessagePlugin.error('查询数据失败')
  } finally {
    queryingData.value = false
  }
}

// 调用云函数
const callCloudFunction = async () => {
  functionCalling.value = true
  addLog(`调用云函数: ${cloudFunctionName.value}`, 'info')
  
  try {
    await new Promise(resolve => setTimeout(resolve, 1800))
    
    const result = {
      functionName: cloudFunctionName.value,
      result: 'Hello from cloud function!',
      requestId: 'req_' + Date.now(),
      duration: 150,
      memoryUsage: '64MB'
    }
    
    functionResult.value = result
    addLog('云函数调用成功', 'success')
    MessagePlugin.success('云函数调用成功')
  } catch (error) {
    addLog(`云函数调用失败: ${error.message}`, 'error')
    MessagePlugin.error('云函数调用失败')
  } finally {
    functionCalling.value = false
  }
}

// 获取云函数列表
const listCloudFunctions = async () => {
  listingFunctions.value = true
  addLog('获取云函数列表...', 'info')
  
  try {
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const result = {
      functions: [
        { name: 'hello', status: 'active', updateTime: '2024-01-15' },
        { name: 'getUserInfo', status: 'active', updateTime: '2024-01-14' },
        { name: 'sendMessage', status: 'inactive', updateTime: '2024-01-10' }
      ]
    }
    
    functionResult.value = result
    addLog('云函数列表获取成功', 'success')
    MessagePlugin.success('云函数列表获取成功')
  } catch (error) {
    addLog(`获取函数列表失败: ${error.message}`, 'error')
    MessagePlugin.error('获取函数列表失败')
  } finally {
    listingFunctions.value = false
  }
}

// 上传到云存储
const uploadToCloud = async () => {
  uploading.value = true
  addLog('上传文件到云存储...', 'info')
  
  try {
    await new Promise(resolve => setTimeout(resolve, 2500))
    
    const result = {
      fileID: 'cloud://test-env.test-bucket/image_' + Date.now() + '.jpg',
      size: '1.2MB',
      url: 'https://example.com/cloud-file.jpg',
      uploadTime: new Date().toISOString()
    }
    
    storageResult.value = result
    addLog('文件上传成功', 'success')
    MessagePlugin.success('文件上传成功')
  } catch (error) {
    addLog(`文件上传失败: ${error.message}`, 'error')
    MessagePlugin.error('文件上传失败')
  } finally {
    uploading.value = false
  }
}

// 获取云文件列表
const listCloudFiles = async () => {
  listingFiles.value = true
  addLog('获取云文件列表...', 'info')
  
  try {
    await new Promise(resolve => setTimeout(resolve, 1300))
    
    const result = {
      files: [
        { fileID: 'cloud://test/image1.jpg', size: '2.1MB', uploadTime: '2024-01-15' },
        { fileID: 'cloud://test/document.pdf', size: '5.3MB', uploadTime: '2024-01-14' },
        { fileID: 'cloud://test/avatar.png', size: '0.8MB', uploadTime: '2024-01-13' }
      ]
    }
    
    storageResult.value = result
    addLog('云文件列表获取成功', 'success')
    MessagePlugin.success('云文件列表获取成功')
  } catch (error) {
    addLog(`获取文件列表失败: ${error.message}`, 'error')
    MessagePlugin.error('获取文件列表失败')
  } finally {
    listingFiles.value = false
  }
}

// 获取当前用户
const getCurrentUser = async () => {
  gettingUser.value = true
  addLog('获取当前用户信息...', 'info')
  
  try {
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const result = {
      openid: 'o6_bmjrPTlm6_2sgVt7hMZOPfL2M',
      nickName: '微信用户',
      avatarUrl: 'https://example.com/avatar.jpg',
      gender: 1,
      country: '中国',
      province: '贵州',
      city: '贵阳'
    }
    
    userResult.value = result
    addLog('用户信息获取成功', 'success')
    MessagePlugin.success('用户信息获取成功')
  } catch (error) {
    addLog(`获取用户信息失败: ${error.message}`, 'error')
    MessagePlugin.error('获取用户信息失败')
  } finally {
    gettingUser.value = false
  }
}

// 获取用户列表
const getUserList = async () => {
  gettingUserList.value = true
  addLog('获取用户列表...', 'info')
  
  try {
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    const result = {
      total: 150,
      users: [
        { openid: 'user1', nickName: '用户1', lastLogin: '2024-01-15' },
        { openid: 'user2', nickName: '用户2', lastLogin: '2024-01-14' },
        { openid: 'user3', nickName: '用户3', lastLogin: '2024-01-13' }
      ]
    }
    
    userResult.value = result
    addLog('用户列表获取成功', 'success')
    MessagePlugin.success('用户列表获取成功')
  } catch (error) {
    addLog(`获取用户列表失败: ${error.message}`, 'error')
    MessagePlugin.error('获取用户列表失败')
  } finally {
    gettingUserList.value = false
  }
}

// 测试用户认证
const testUserAuth = async () => {
  testingAuth.value = true
  addLog('测试用户认证...', 'info')
  
  try {
    await new Promise(resolve => setTimeout(resolve, 1200))
    
    const result = {
      authenticated: true,
      token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
      expiresIn: 7200,
      permissions: ['read', 'write', 'admin']
    }
    
    userResult.value = result
    addLog('用户认证测试完成', 'success')
    MessagePlugin.success('用户认证测试完成')
  } catch (error) {
    addLog(`用户认证测试失败: ${error.message}`, 'error')
    MessagePlugin.error('用户认证测试失败')
  } finally {
    testingAuth.value = false
  }
}

// 保存云配置
const saveCloudConfig = () => {
  localStorage.setItem('wechat_cloud_config', JSON.stringify(cloudConfig))
  addLog('云配置已保存', 'success')
  MessagePlugin.success('配置保存成功')
}

// 加载云配置
const loadCloudConfig = () => {
  const saved = localStorage.getItem('wechat_cloud_config')
  if (saved) {
    Object.assign(cloudConfig, JSON.parse(saved))
    addLog('云配置已加载', 'success')
    MessagePlugin.success('配置加载成功')
  } else {
    addLog('未找到保存的配置', 'warning')
    MessagePlugin.warning('未找到保存的配置')
  }
}

// 组件挂载时加载配置
onMounted(() => {
  loadCloudConfig()
  addLog('微信云测试界面已加载', 'info')
})
</script>

<style scoped>
.wechat-cloud-test {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.test-card {
  margin-bottom: 20px;
}

.connection-status {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
}

.status-text {
  color: #666;
  font-size: 14px;
}

.test-sections {
  margin-bottom: 20px;
}

.function-card {
  height: 100%;
  min-height: 400px;
}

.test-actions {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 20px;
}

.function-input {
  margin-bottom: 12px;
}

.test-result {
  background: #f8f9fa;
  border-radius: 6px;
  padding: 12px;
  max-height: 200px;
  overflow-y: auto;
}

.test-result pre {
  margin: 0;
  font-size: 12px;
  color: #333;
  white-space: pre-wrap;
  word-break: break-all;
}

.config-card {
  margin-bottom: 20px;
}

.log-card {
  margin-bottom: 20px;
}

.log-container {
  max-height: 300px;
  overflow-y: auto;
  background: #1e1e1e;
  border-radius: 6px;
  padding: 12px;
}

.log-item {
  display: flex;
  gap: 12px;
  margin-bottom: 8px;
  font-family: 'Courier New', monospace;
  font-size: 12px;
}

.log-time {
  color: #888;
  min-width: 80px;
}

.log-message {
  flex: 1;
}

.log-info .log-message {
  color: #61dafb;
}

.log-success .log-message {
  color: #52c41a;
}

.log-warning .log-message {
  color: #faad14;
}

.log-error .log-message {
  color: #ff4d4f;
}

.no-logs {
  text-align: center;
  color: #888;
  font-style: italic;
  padding: 20px;
}

:deep(.t-card__header) {
  border-bottom: 1px solid #e6e6e6;
}

:deep(.t-card__body) {
  padding: 20px;
}
</style>
